package com.example.chapter14;

import java.sql.*;

/**
 * JDBC连接mysql
 * @date 2024/4/30
 */
public class Demo01 {

    /**
     * CREATE TABLE `student` (
     *   `id` int(11) NOT NULL AUTO_INCREMENT,
     *   `username` varchar(255) DEFAULT NULL,
     *   `password` varchar(255) DEFAULT NULL,
     *   PRIMARY KEY (`id`)
     * ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
     * @param args
     */
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.jdbc.Driver"); //1. 加载驱动
            //2. 获取连接
            String url = "jdbc:mysql://localhost:3306/user_model?useUnicode=true&characterEncoding=UTF-8&useSSL=false";
            String user = "root"; //数据库账号
            String password = "root"; //数据库密码
            try {
                //连接对象输入三个参数
                Connection connection = DriverManager.getConnection(url, user, password);
                System.out.println(connection);
                //定义sql语句
                // 查询学生表中的所有数据
                String sql1 = "select * from student";
                //3. 创建statement对象
                Statement statement = connection.createStatement();
                //4. 执行sql语句
                ResultSet resultSet = statement.executeQuery(sql1);
                System.out.println(resultSet);
                //5. 处理结果集
                while (resultSet.next()) {
                    //下标或者字段
                    int id = resultSet.getInt("id");
                    String username = resultSet.getString("username");
                    String password1 = resultSet.getString(3);
                    System.out.println(id + "-" + username + "-" + password1);
                }

                //6. 释放资源
                statement.close();
                connection.close();
                resultSet.close();

            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

